package com.tools.common.container;

import com.tools.common.object.Note;

import java.util.Map;
import java.util.Objects;

/**
 * 对于 Map.Entry 的一种实现
 * */
@Note("对于 Map.Entry 的一种实现")
public class MapEntry<K, V> implements Map.Entry<K, V> {

    private final K key;

    private V value;

    public MapEntry(K key, V value) {
        this.key = key;
        this.value = value;
    }

    public MapEntry(Map.Entry<K, V> entry) {
        if(entry == null) throw new NullPointerException("entry 不能为 null");
        this.key = entry.getKey();
        this.value = entry.getValue();
    }

    @Override
    public K getKey() {
        return key;
    }

    @Override
    public V getValue() {
        return value;
    }

    @Override
    public V setValue(V value) {
        V old = this.value;
        this.value = value;
        return old;
    }


    @Override
    public String toString() {
        return key + "=" + value;
    }

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof Map.Entry)) return false;
        Map.Entry<?, ?> e = (Map.Entry<?, ?>) o;
        return Objects.equals(key, e.getKey()) && Objects.equals(value, e.getValue());
    }

    @Override
    public int hashCode() {
        return (key == null ? 0 : key.hashCode()) ^
                (value == null ? 0 : value.hashCode());
    }
}
